<template>
  <div class="pagination">
    <!-- 上一页按钮 -->
    <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
    <!-- 页码列表 -->
    <ul>
      <li
          v-for="page in visiblePages"
          :key="page"
          :class="{ active: page === currentPage }"
          @click="goToPage(page)"
      >
        {{ page }}
      </li>
    </ul>
    <!-- 下一页按钮 -->
    <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';

// 接收的 props
const props = defineProps({
  currentPage: {
    type: Number,
    default: 1
  },
  pageSize: {
    type: Number,
    default: 10
  },
  totalRecords: {
    type: Number,
    default: 0
  },
  maxVisiblePages: {
    type: Number,
    default: 5
  }
});

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(props.totalRecords / props.pageSize);
});

// 计算可见的页码列表
const visiblePages = computed(() => {
  const startPage = Math.max(
      1,
      props.currentPage - Math.floor(props.maxVisiblePages / 2)
  );
  const endPage = Math.min(
      startPage + props.maxVisiblePages - 1,
      totalPages.value
  );
  return Array.from(
      { length: endPage - startPage + 1 },
      (_, index) => startPage + index
  );
});

// 上一页
const prevPage = () => {
  if (props.currentPage > 1) {
    emit('page-change', props.currentPage - 1);
  }
};

// 下一页
const nextPage = () => {
  if (props.currentPage < totalPages.value) {
    emit('page-change', props.currentPage + 1);
  }
};

// 跳转到指定页码
const goToPage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    emit('page-change', page);
  }
};

// 发出页码改变事件
const emit = defineEmits(['page-change']);
</script>

<style scoped>
.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
}

.pagination button {
  margin: 0 5px;
  padding: 5px 10px;
  cursor: pointer;
}

.pagination ul {
  display: flex;
  list-style-type: none;
  margin: 0;
  padding: 0;
}

.pagination li {
  margin: 0 5px;
  padding: 5px 10px;
  cursor: pointer;
  border: 1px solid #ccc;
}

.pagination li.active {
  background-color: #007bff;
  color: white;
}
</style>